package org.yan.stock.server.client;

import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.yan.stock.server.core.PMF;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;


public class DefaultClientService {
	
	private static final Logger log = Logger.getLogger(DefaultClientService.class.getSimpleName());
	
	/**
	 * merge the client info. 
	 * @param client
	 */
	public void merge(Client client) {
		Key key = KeyFactory.createKey(Client.class.getSimpleName(), client.getAuthId());
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Client oldClient = pm.getObjectById(Client.class, key);
		if(oldClient != null) {
			oldClient.setLatchs(client.getLatchs());
			oldClient.setStocks(client.getStocks());
			oldClient.setUpDate(new Date());
			pm.makePersistent(oldClient);
			log.log(Level.SEVERE, "Update old client:" + oldClient.getSenderId());
		}
		else {
			client.setKey(key);
			client.setRegDate(new Date());
			pm.makePersistent(client);
			log.log(Level.SEVERE, "Add new client:" + client.getSenderId());
		}
		pm.close();
	}
	
	/**
	 * Remove the client
	 */
	public void remove(Client client) {
		Key key = KeyFactory.createKey(Client.class.getSimpleName(), client.getAuthId());
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Client oldClient = pm.getObjectById(Client.class, key);
		if(oldClient != null) {
			pm.deletePersistent(oldClient);
			log.log(Level.SEVERE, "Delete client using key:" + key.toString());
		}
		else {
			Query query = pm.newQuery(Client.class,"senderId = mail");
			query.declareParameters("String mail");
			query.deletePersistentAll(client.getSenderId());
			log.log(Level.SEVERE, "Delete client using senderId:" + client.getSenderId());
		}
		pm.close();
	} 
	
	/**
	 * Get the threshold size of client
	 */
	@SuppressWarnings("unchecked")
	public List<Client> fetchClientList(int threshold) {
		int count = 0;
		List<Client> clientList = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Client.class,"paidType='1'");
		query.setRange(0, threshold);
		List<Client> paidClientList = (List<Client>)query.execute();
		count = threshold - paidClientList.size();
		if(count > 0) {
			query = pm.newQuery(Client.class,"paidType='0'");
			query.setRange(0, count);
			List<Client> freeClientList = (List<Client>)query.execute();
			clientList = paidClientList;
			clientList.addAll(freeClientList);
		}
		else {
			clientList = paidClientList;
		}
		pm.close();
		return clientList;
	}
}
